<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">

     <el-form-item label="周数" prop="date">
        <span id="currentWeekly">
          第{{this.queryParams.weeks}}周
         </span>
     </el-form-item>

      <el-form-item label="日期" prop="date">
         <span id="currentWeekly">
           <el-date-picker
                v-model="defaultDateStr"
                type="date"
                :format="formatWeek"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
                :default-value="defaultDate"
                @change="handleQuery"
                :clearable="false">
            </el-date-picker>
          </span>
      </el-form-item>

      <el-form-item label="名称" prop="name">
        <el-select v-model="queryParams.name" filterable placeholder="请选择" @change="handleQuery('DATE')" :clearable="true">
            <el-option
              v-for="item in nameOptions"
              :key="item.userId"
              :label="item.name"
              :value="item.name"
              >
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['module:arrange:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['module:arrange:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
    v-loading="loading"
    :data="arrangeList"
    ref="tableMain"
    row-key="id"
   :default-expand-all="isExpandAll"
   :span-method="arraySpanMethod"
    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="名称" align="center" prop="name" width="120"  fixed/>
      <el-table-column label="时间" align="center" prop="date" width="200"  fixed>
      <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date,'{m}月{d}日（星期{a}）') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上午" align="center" prop="morning" />
      <el-table-column label="下午" align="center" prop="afternoon"/>
      <el-table-column label="更新人员" align="center" prop="updateUser" width="120"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180"  fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd(scope.row)"
            v-if="scope.row.hasChild"
            v-hasPermi="['module:arrange:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="!scope.row.hasChild"
            v-hasPermi="['module:arrange:add']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="!scope.row.hasChild"
            v-hasPermi="['module:arrange:delete']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

  <!--  <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    /> -->

    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="mname">
          <span>{{form.mname}}</span>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
               v-model="form.date"
               type="date"
               value-format="yyyy-MM-dd"
               placeholder="选择日期"
               @change="searchEntity"
               :clearable="false">
             </el-date-picker>
        </el-form-item>
        <el-form-item label="上午行程" prop="morning">
          <el-input type="textarea" v-model="form.morning" placeholder="请输入工作行程" autosize />
        </el-form-item>
        <el-form-item label="下午行程" prop="afternoon">
          <el-input type="textarea" v-model="form.afternoon" placeholder="请输入工作行程" autosize />
        </el-form-item>
        <el-form-item label="当天行程" prop="allday">
          <el-input type="textarea" v-model="form.allday" placeholder="请输入工作行程;注意:若有输入当天行程,上午及下午行程内容将自动作废" autosize/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?year=' + upload.year"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
         <div class="el-upload__tip" slot="tip">
            <el-input type="number" v-model="upload.year" placeholder="请输入导入内容的所属年份" />
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <span>：
            <el-progress :percentage="upload.currentProgress"></el-progress>
          </span>
        <!--  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { arrangeApi } from "@/api/module/index";
import { memberApi } from "@/api/module/index";
import { getToken } from "@/utils/auth";

export default {
  name: "Arrange",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],

      items:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      arrangeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //折叠
      isExpandAll:true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 266,
        name: null,
        dateStr:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        date: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
      },

      formatWeek:"yyyy年MM月dd日",

      //默认日期
      defaultDateStr:null,
      defaultDate:null,

      //搜索选项
      nameOptions:[],
      downloanDate:null,

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        //年份
        year:"",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/arrange/importData",

        currentProgress:0
      },

      webSocket:{
        url: "ws://139.159.248.193:9090/stage-api/websocket/message",
        ws: null,
      }


    };
  },
  created() {
    //获取下周日期
    this.getNextWeeks();
    this.getNameOption();
    this.getList();


  },
  mounted(){
    //this.joinWebSocket();
  },
  methods: {
    joinWebSocket() {
      const wsuri = this.webSocket.url;
      this.webSocket.ws = new WebSocket(wsuri);
      const self = this;
      this.webSocket.ws.onopen = function (event) {
        self.text_content = self.text_content + "已经打开连接!" + "\n";
      };
      this.webSocket.ws.onmessage = function (event) {
        setTimeout(function(){
          var eventData = event.data;
          if(eventData != null && '' != eventData && '连接成功' != eventData){
            const data = JSON.parse(eventData);
            self.upload.currentProgress = data;
          }
        },450);

      };
      this.webSocket.ws.onclose = function (event) {
        self.text_content = self.text_content + "已经关闭连接!" + "\n";
      };
    },
    getNameOption(){
      let search = new Object();
      search.status = '0';//状态显示
      search.pageNum = 1;
      search.pageSize = 50;
      memberApi.listMember(search).then(response => {
        this.nameOptions = response.rows;
      });
    },
    /* getNextWeeks(){
    	//获取下周日期
    	let currentDate = new Date();
    	let currentDateStr = this.parseTime(currentDate);
    	this.queryParams.weeks = this.getWeeks(currentDateStr) + 1;
    	const oneDayMilliseconds = 24 * 60 * 60 * 1000;
    	const nextSevenDayTime = currentDate.getTime() + oneDayMilliseconds * 7;
      let nextSevenDate = new Date(nextSevenDayTime)
    	this.queryParams.date = this.parseTime(nextSevenDate);
      this.defaultDateStr = nextSevenDate;
      this.defaultDate = nextSevenDate
    }, */

    searchEntity(){
      if(this.form.date){
        this.$modal.loading("匹配数据中...");
        let mname = this.form.mname;
        let morning = this.form.morning;
        let afternoon = this.form.afternoon;
        let allday = this.form.allday;
        let id = this.form.id;

        let search = new Object();
        search.date = this.form.date;
        search.userId = this.form.userId;
        arrangeApi.listArrange(search).then(response => {
          if(response.rows.length > 0){
            this.form = response.rows[0].children[0];
          }else{

            this.reset();
            this.form.mname = mname;
            this.form.userId = search.userId;
            this.form.date = search.date;

            if(!id){
            	this.form.morning = morning;
            	this.form.afternoon = afternoon;
            	this.form.allday = allday;
            }
            this.form.weeks = this.getWeeks(this.form.date);
          }
          this.$modal.closeLoading()
        })
      }
    },
    getNextWeeks(){
    	//获取当周日期
    	let currentDate = new Date();
      let weeksDate = this.parseTime(currentDate,'{a}');
    	let currentDateStr = this.parseTime(currentDate);
      if("日" == weeksDate){
        this.queryParams.weeks = this.getWeeks(currentDateStr) + 1;
        const oneDayMilliseconds = 24 * 60 * 60 * 1000;
        const nextSevenDayTime = currentDate.getTime() + oneDayMilliseconds * 7;
        this.defaultDateStr = this.parseTime(new Date(nextSevenDayTime));
        this.defaultDate = this.defaultDateStr;
      }else{
        this.queryParams.weeks = this.getWeeks(currentDateStr);
        this.defaultDateStr = currentDate;
        this.defaultDate = currentDate;
      }
      this.queryParams.year = currentDateStr.substr(0,4);
    },

    getWeeks(val){
    	var year = val.substr(0,4);
    	var month = val.substr(5,2);
    	var day = val.substr(8,2);
    	let weeks = this.getYearWeeks(year,month,day);
    	return weeks;
    },

    //合并列方法
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if(!row.hasChild ){
        if(row.allday){
          row.morning = row.allday;
          if (columnIndex === 2) {
            return [1, 2];
          } else if (columnIndex === 3) {
            return [0, 0];
          }
        }
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      arrangeApi.listArrange(this.queryParams).then(response => {

        let list = response.rows;
        for(let i of list){
          i.hasChild = true;
        }
        this.arrangeList = response.rows;
        //this.total = response.total;

        this.total = response.rows.length;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        mname: null,
        timeSlot:null,
        date: null,
        content: null,
        weeks: null,
        updateUid: null,
        updateUser: null,
        createTime: null,
        updateTime: null,
        del: null,
        morning:null,
        afternoon:null,
        allday:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery(e) {
      if('DATE' != e){
        this.queryParams.weeks = this.getWeeks(this.defaultDateStr);
        this.queryParams.year = e.substr(0,4);
      }
      this.queryParams.pageNum = 1;
      this.queryParams.date = null;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.form.userId = row.userId;
      this.form.mname = row.name;
      this.open = true;
      this.title = "添加工作行程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改工作行程";
      this.open = true;
      this.form = {...row};

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          //获取周数
          var year = this.form.date.substr(0,4);
          var month = this.form.date.substr(5,2);
          var day = this.form.date.substr(8,2);
          this.form.weeks = this.getYearWeeks(year,month,day);
          arrangeApi.saveArrange(this.form).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.getList();
          });

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return arrangeApi.delArrange(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      let downloadParams = this.queryParams;
      downloadParams.date = this.parseTime(this.defaultDateStr);
      this.download('arrange/export', {
        ...downloadParams
      }, `第`+ downloadParams.weeks +`周市领导下周工作预安排.xlsx`);
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "工作日程导入";
      this.upload.currentProgress = 0;
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if(!this.upload.year){
         this.$modal.msgWarning("请输入年份");
         return false;
      }
      this.$refs.upload.submit();
    }
  }
};
</script>
<style scoped>
  /deep/ .el-table__header-wrapper  .el-checkbox{
     display:none
   }
</style>
